package com.example.administrator.fragmentwx;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private ListView mListView;
    private TextView tvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找到头部文本
        tvTitle = findViewById(R.id.tv_title);
        //页面初始化时，需要载入一个页面
        init();

        //找到按钮，为按钮添加监听
        RadioGroup rg = (RadioGroup)findViewById(R.id.rg);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton)group.findViewById(checkedId);
                String str = rb.getText().toString();
                tvTitle.setText(str);
                //第一步 创建FragmentManager对象
                FragmentManager fm =getFragmentManager();
                // 创建FragmentTransaction
                FragmentTransaction ft =fm.beginTransaction();
                //载入

                //判断哪一个按钮被点击
                switch (checkedId){
                    case R.id.btn1:
                        ft.replace(R.id.fl_main,new Fragment1());
                        break;
                    case R.id.btn2:
                        ft.replace(R.id.fl_main,new Fragment2());
                        break;
                    case R.id.btn3:
                        ft.replace(R.id.fl_main,new Fragment3());
                        break;
                    case R.id.btn4:
                        ft.replace(R.id.fl_main,new Fragment4());
                        break;
                }
                //开启事务
                ft.commit();
            }
        });
    }

    private void init() {
        FragmentManager fm =getFragmentManager();
        // 创建FragmentTransaction
        FragmentTransaction ft =fm.beginTransaction();
        ft.replace(R.id.fl_main,new Fragment1());
        ft.commit();
    }
}
